package com.sites.cms.common;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.kit.Ret;
import com.jfinal.render.JsonRender;
import com.jfinal.render.Render;
import com.sites.common.SiteInfo;

/**
 * 返回信息处理拦截器
 * 用于处理失败请求，请求失败的需要更新formtoken
 */
public class ReturnInterceptor implements Interceptor {

    @Override
    public void intercept(Invocation invocation) {
        invocation.invoke();

        Controller controller = invocation.getController();
        Render render = controller.getRender();
        if(render instanceof JsonRender){
            JsonRender jsonRender = (JsonRender) render;
            String jsonText = jsonRender.getJsonText();
            JSONObject jsonObject = JSONUtil.parseObj(jsonText);
            String state = (String) jsonObject.get("state");
            if("fail".equals(state)){
                jsonObject.set(SiteInfo.formTokenKey, controller.createToken(SiteInfo.formTokenKey, 1800));
                controller.renderJson(jsonObject);
            }
        }
    }

}
